import axios from 'axios'
import { Loading } from 'element-ui'
// import { Message, Loading } from 'element-ui'
// 限制不能同时出现多个相同的报错信息
import { message } from '@/utils/resetMessage'
import store from '@/store'
import { getSessionId, getAuthSessionId, blobToObj, getUserInfo } from '@/utils/auth'
import global from '@/global'
import vm from '../main.js'
import Middle from '@/utils/middle.js'
import i18n from '@/lang/index'

// 下载的接口中所有content-type，不在列表里的将走正常接口流程
let downList = ['text/csv; charset=utf-8', 'application/x-zip-compressed', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/csv;charset=GBK', 'application/vnd.tcpdump.pcap', 'text/html', 'application/pdf', 'application/msword']

// 列表中包含的报错信息重新登录
let reLogin = ['会话（socket连接）不存在,请重新登录', '缺少session_id参数', '用户类型不兼容，请联系开发人员！']

// 不需要加载动画的接口（登录接口 抓包接口 首页所有接口等）
let loadingInstanceList = ['/member/login', '/member/getPublicKey', '/member/getImageCode', '/debug/getPackageInfo', '/member/getMenu', '/home/homeMenu', '/update/getFirmwareInfo', '/home/runTime', '/home/getTime', '/home/getInfo', '/home/runTime', '/home/getTime', '/home/getInfo', '/home/flow', '/home/cpu', '/home/mem', '/home/trend', '/home/storage', '/home/log_level', '/home/licence', '/connection/getAllCount', '/flow/getArray', '/debug/getDubugInfo', '/hot/getStatus', '/dp_log/sessionChild', '/report_log/searchEvent', '/report_log/module', '/report_log/searchL4type', '/debug/listenPackageInfo', '/debug/checkPackage', '/assist/getServerChildArray', '/policy/reloadPolicyShow', '/member/ukeyCheck', '/userAuth/checkAlive', '/hot/getConfigureSendStatus', '/hot/showConfigure']
let authList = ['/userAuth/authLogin', '/userAuth/getRandom', '/userAuth/keepAlive', '/userAuth/checkAlive', '/userAuth/logout']
// let loadingFullList = ['/addr/editAddrInfo', '/addr/addAddrInfo', '/addr_group/editAddrGroup', '/addr_group/addAddrGroup', '/asset_group/addAssetGroup', '/asset_group/editAssetGroup', '/asset_object/addAsset', '/asset_object/editAsset', '/responsible/addResponsible', '/responsible/editResponsible', '/app_blue/addApp', '/app_blue/editApp', '/safe/addSafe', '/safe/editSafe', '/service/addService', '/service/editService', '/time_blue/addTime', '/time_blue/editTime']
// 不需要ukey_chack校验的接口
let ArmEnumCheckList = ['/member/logout', '/member/oem', '/member/getPublicKey', '/member/login', '/home/homeMenu', '/member/getMenu', '/update/getFirmwareInfo', '/userAuth/authLogin', '/userAuth/getRandom', '/userAuth/keepAlive', '/userAuth/checkAlive', '/userAuth/logout', '/member/ukeyCheck', '/userAuth/logout', '/member/logout']

let nowLoadingList = 0 // 统计进入加载中接口数量
let nowUkeyList = 0 // 统计验证ukey的接口数量
let loadingInstance = null // 加载中模块对象
const timeout = 1000 * 60 * 10;
// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: global.BASE_URL,
  // withCredentials: true, // 跨域请求时发送cookies
  timeout, // 请求超时
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencode'
    // 'Access-Control-Allow-Origin': '*'
  }
})

// service.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    if (!ArmEnumCheckList.includes(config.url) && getUserInfo() && getUserInfo().ukey !== 0) {
      if (nowUkeyList === 0) {
        vm.OnLoadCheck().then(res => {
          // 延时100毫秒
          setTimeout(function () {
            vm.Arm_Enum_Check()
          }, 100)
        })
      }
      nowUkeyList += 1
    }
    if (!loadingInstanceList.includes(config.url)) {
      nowLoadingList += 1
      if (!loadingInstance) { // && document.getElementById('main-height')
        loadingInstance = Loading.service({
          // 根据路由中包含add和edit判断是否需要全屏loading
          // target: (config.url.slice(1).indexOf('/add') > 0 || config.url.slice(1).indexOf('/edit') > 0) ? 'app' : (document.getElementsByClassName('el-dialog')[0] ? '.el-dialog' : '#tagsAndRouterView'),
          fullscreen: true,
          lock: true,
          text: vm.$t('加载'),
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.4)',
          customClass: 'requestLoading'
        })
      }
    }
    if (authList.includes(config.url) && getAuthSessionId()) {
      config.headers['session_id'] = getAuthSessionId()
    } else if (getSessionId()) {
      // config.data.set('session_id', getSessionId())
      config.headers['session_id'] = getSessionId()
      // config.headers['Content-Type'] = 'application/x-www-form-urlencode'
    }
    // config.headers['Access-Control-Allow-Origin'] = '*'
    return config
  },
  error => {
    // 处理请求错误
    // console.log(error) // 用于调试
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * 如果您想获取http信息，如 headers 或 status
   * Please return  response => response
  */

  /**
   *通过自定义代码确定请求状态
   *还可以通过HTTP状态码来判断状态
   */
  response => {
    const res = response.data
    // 判断加载动画数量并关闭
    if (!loadingInstanceList.includes(response.config.url)) {
      nowLoadingList -= 1
      if (loadingInstance && nowLoadingList <= 0) {
        loadingInstance.close()
        loadingInstance = null
      }
    }
    if (!ArmEnumCheckList.includes(response.config.url) && getUserInfo() && getUserInfo().ukey !== 0) {
      nowUkeyList -= 1
    }
    if (res.status === -99 || res.status === '-99' || reLogin.includes(res.msg)) {
      // 重新登录
      if (authList.includes(response.config.url)) {
        store.dispatch('user/logoutAuth').then(() => {
          location.reload()
          return Promise.reject(new Error(res.msg || 'Error'))
        })
      } else if (getSessionId()) {
        if (response.config.url !== '/member/logout') {
          // MessageBox.confirm('您已注销，可以取消以停留在此页面，或重新登录', '确认注销', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '重新登录',
          //   cancelButtonText: '取消',
          //   cancelButtonClass: 'confirmCancelButton',
          //   type: 'warning'
          // }).then(() => {
          store.dispatch('user/logout').then(() => {
            location.reload()
            return Promise.reject(new Error(res.msg || 'Error'))
          })
          // })
        }
      } else {
        store.dispatch('user/logout').then(() => {
          location.reload()
          return Promise.reject(new Error(res.msg || 'Error'))
        })
      }
      // }
    } else if (res.status === -1) {
      // 如果自定义代码是-1，则判断为错误
      message.error(i18n.t(res.msg) || 'Error')
      return Promise.reject(new Error(i18n.t(res.msg) || 'Error'))
    } else if (res.status === -1000) {
      // 自定义代码是-100，报错弹出提示框（物理接口用）
      // res.status === -100 && ['physical/editPhysicalApi',].includes(response.config.url)
      return Promise.reject(res)
    } else if (res.status === -80) {
      Middle.$emit('showErrorList', res)
      return Promise.reject(new Error(res.msg || 'Error'))
    } else if (res.status === 0) {
      return res
    } else if (res.status > 0) {
      message.warning(res.msg ? (i18n.t('配置成功，警告：') + i18n.t(res.msg)) : 'Warning')
      return res
    } else if (downList.includes(response.headers['content-type']) && response.status === 200) {
      var filename = decodeURIComponent(response.headers['content-disposition'].replace('attachment; filename=', ''))
      return [res, filename, response.headers['content-type']]
    } else if (res.status === -20) {
      message.error(res.msg || 'Error')
      return Promise.reject(res)
    } else {
      if (res instanceof Blob) {
        let blob = blobToObj(res)
        blob.then(res1 => {
          message.error(i18n.t(res1.msg) || 'Error')
        })
      } else {
        message.error(i18n.t(res.msg) || 'Error')
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  error => {
    // console.log('err' + error) // for debug
    if (!loadingInstanceList.includes(error.config.url)) {
      if (loadingInstance) {
        nowLoadingList -= 1
        if (loadingInstance && nowLoadingList <= 0) {
          loadingInstance.close()
          loadingInstance = null
        }
      }
    }
    if (String(error).includes('timeout')) {
      message.error(i18n.t('连接超时！'))
    } else if (String(error).includes('Network Error')) {
      message.error(i18n.t('网络故障！'))
    } else {
      message.error(i18n.t('服务器异常！'))
    }
    return Promise.reject(error)
  }
)

export default service
